package com.gp.study.tomcat.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import com.gp.study.tomcat.bean.GpServletRegistry;
import com.gp.study.tomcat.servlet.GpServlet;
import com.gp.study.tomcat.utils.GPIOUtils;

public class GpRequestHandler implements Runnable {
	
	private Socket socket;

	public GpRequestHandler(Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		// 处理请求
		//解析 封装 请求 req
		String reqStr;
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			inputStream=socket.getInputStream();
			outputStream = socket.getOutputStream();
			reqStr = GPIOUtils.getInputStremContent(inputStream);
			System.out.println("收到请求内容："+reqStr);
			GPHttpServletRequest servletRequest = GPIOUtils.getServletRequest(reqStr);
			GPHttpServletResponse servletResponse = new GPHttpServletResponse(outputStream);
			
			String url = servletRequest.getURL();
			if(GpServletRegistry.containsKey(url)){
				GpServlet servlet = GpServletRegistry.getServlet(url);
				servlet.doService(servletRequest, servletResponse);
			}else{
				servletResponse.write("404 not found");
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				outputStream.flush();
				outputStream.close();
				inputStream.close();
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		
		
		// 返回响应

	}

}
